package school.community.controller;

import school.community.dto.GiteeAccessTokenDTO;
import school.community.dto.GiteeUser;
import school.community.model.User;
import school.community.provider.GiteeProvider;
import school.community.service.NotificationService;
import school.community.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * Created by codedrinker on 2019/4/24.
 */
@Controller
@Slf4j
public class AuthorizeController {

  @Autowired
  private GiteeProvider giteeProvider;

  @Autowired
  private NotificationService notificationService;

  @Value("${gitee.client.id}")
  private String clientId;

  //${key}从applicaltion.properties中获取值
  @Value("${gitee.client.secret}")
  private String clientSecret;

  @Value("${gitee.redirect.uri}")
  private String redirectUri;

  @Autowired
  private UserService userService;

  @GetMapping("/oauth/callback/gitee")
  public String callback(@RequestParam(name = "code") String code,
                         @RequestParam(name = "state") String state,
                         HttpSession session,
                         HttpServletResponse response) {

    GiteeAccessTokenDTO giteeAccessTokenDTO = new GiteeAccessTokenDTO(clientId, clientSecret, code, redirectUri, state);
    String accessToken = giteeProvider.getAccessToken(giteeAccessTokenDTO);
    GiteeUser giteeUser = giteeProvider.getUser(accessToken);
    if (giteeUser != null && giteeUser.getId() != null) {
      User user = new User();
      String token = UUID.randomUUID().toString();
      user.setToken(token);
      user.setName(giteeUser.getName());
      user.setAccountId(String.valueOf(giteeUser.getId()));
      user.setAvatarUrl(giteeUser.getAvatarUrl());
      userService.createOrUpdate(user);
      User dbUser = userService.getUserByAccountId(user);
      Cookie cookie = new Cookie("token", token);
      cookie.setMaxAge(60 * 60 * 24 * 30 * 6);
      response.addCookie(cookie);
      session.setAttribute("user", dbUser);
      Long unreadCount = notificationService.unreadCount(dbUser.getId());
      session.setAttribute("unreadCount", unreadCount);
      return "redirect:/";
    } else {
      log.error("callback get github error,{}", giteeUser);
      // 登录失败，重新登录
      return "redirect:/";
    }
  }

  @GetMapping("/logout")
  public String logout(HttpServletRequest request,
                       HttpServletResponse response) {
    request.getSession().removeAttribute("user");
    request.getSession().removeAttribute("admin");
    Cookie cookie = new Cookie("token", null);
    cookie.setMaxAge(0);
    response.addCookie(cookie);
    return "redirect:/";
  }
}
